import {
	getToken,
	removeToken
} from '@/utils/auth.js';

const baseUrl = 'http://localhost:10001';

class HttpRequest {
	api(options = {}) {
		// 监听网络链接（选做）
		uni.onNetworkStatusChange((res) => {
			if (!res.isConnected) {
				uni.showToast({
					icon: 'none',
					title: '网络连接不可用！'
				})
			}
			return false;
		});
		// 定义参数对象
		if (!options.method) {
			options.method = 'GET';
		}
		options.url = `${baseUrl}${options.url}`;
		const token = getToken();
		if (token) {
			options.header = {
				'Content-Type': 'application/json',
				'Authorization': `Bearer ${token}`
			}
		} else {
			options.header = {
				'Content-Type': 'application/json'
			}
		}
		// 封装请求
		return new Promise((resolve, reject) => {
			uni.showLoading();
			// 请求成功
			options.success = (res) => {
				uni.hideLoading();
				switch (res.data.code) {
					case 200:
						// 有返回结果，则回调结果
						resolve(res.data);
						break;
					case 401:
					case 403:
						// 清除本地token
						removeToken();
						// 关闭所有页面返回到登录页
						uni.reLaunch({
							url: 'pages/login/index'
						});
						break;
					case 500:
					case 404:
					default:
						// 错误提示
						uni.showToast({
							icon: 'error',
							title: res.data.msg
						});
						reject(res);
						break;
				}
			};
			// 请求失败
			options.fail = (err) => {
				uni.hideLoading();
				// 失败提示
				uni.showToast({
					icon: 'error',
					title: '服务器错误,请稍后再试'
				});
				reject(err);
			};
			// 执行请求
			uni.request(options);
		});
	}
	get(url, ...params) {
		let newUrl;
		if (params && params.length > 0) {
			const query = params.join('&');
			newUrl = `${url}?${query}`;
		} else {
			newUrl = url;
		}
		const options = {
			url: newUrl,
			method: 'GET'
		};
		return this.api(options);
	}
	post(url, data) {
		const options = {
			url: url,
			method: 'POST',
			data: data
		};
		return this.api(options);
	}
	put(url, data) {
		const options = {
			url: url,
			method: 'POST',
			data: data
		};
		return this.api(options);
	}
	delete(url) {
		const options = {
			url: url,
			method: 'DELETE'
		};
		return this.api(options);
	}
}
const httpRequest = new HttpRequest();
export default httpRequest;
